package tv.accedo.memory.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tv.accedo.memory.dao.AchiDao;
import tv.accedo.memory.dao.UserDao;
import tv.accedo.memory.model.Achi;

public class AchiShowServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		// System.out.println("Server get one request from client side!");

		String username = request.getParameter("username");
		System.out.println("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + username); 
		Achi achi = new Achi();
		UserDao userDao = new UserDao();
		AchiDao achiDao = new AchiDao();
		List<Achi> achiList = new ArrayList<Achi>();
		Set<Achi> achiSet = new HashSet<Achi>();
		List<String> achiStringList = new ArrayList<String>();
		if (username != "") {
			achiSet = userDao.getUserByUsername(username).getAchis();
		}
		for (Iterator<Achi> iter = achiSet.iterator(); iter.hasNext();) {
			achi = iter.next();
			achiStringList.add(achi.getAchi_sn());
		}
		achiList = achiDao.getAllAchi();

		String jsonString = "]}";
		for (Iterator<Achi> iter = achiList.iterator(); iter.hasNext();) {
			achi = iter.next();
			String achiComp = null;
			if (achiStringList.contains(achi.getAchi_sn())) {
				achiComp = "A";
			} else {
				achiComp = "B";
			}
			jsonString = "{achi_sn:'" + achi.getAchi_sn() + "',achi_name:'"
					+ achi.getAchi_name() + "',achi_state:'" + achiComp + "'},"
					+ jsonString;
		}
		jsonString = "{achis:[" + jsonString;
		System.out.println(jsonString);
		out.print(jsonString);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
